package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.capabilities.battle.IBattleMode;
import cn.anecansaitin.whimsy.common.item.Doomfist;
import cn.anecansaitin.whimsy.common.item.handcannon.HandCannon;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import org.lwjgl.glfw.GLFW;

import java.util.Optional;

public record KeyInputPack(int target, int[] keyInput) implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("key_input_pack");
    public static final ServerHandler HANDLER = new ServerHandler();
    public static final int HAND_CANNON = 0;
    public static final int DOOMFIST = 1;

    public KeyInputPack(FriendlyByteBuf buffer) {
        this(buffer.readVarInt(), buffer.readVarIntArray());
    }

    @Override
    public void write(FriendlyByteBuf buffer) {
        buffer.writeVarInt(target);
        buffer.writeVarIntArray(keyInput);
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static class ServerHandler {
        private ServerHandler() {}

        public void handle(KeyInputPack data, PlayPayloadContext context) {
            context.workHandler().submitAsync(() -> {
                Optional<Player> optionalPlayer = context.player();

                if (optionalPlayer.isEmpty()) {
                    return;
                }

                Player player = optionalPlayer.get();

                switch (data.target) {
                    case HAND_CANNON -> {
                        ItemStack item = player.getOffhandItem();

                        if (!(item.getItem() instanceof HandCannon cannon)) {
                            return;
                        }

                        switch (data.keyInput[0]) {
                            case GLFW.GLFW_MOUSE_BUTTON_LEFT -> cannon.mainAttack(player, item);
                            case GLFW.GLFW_MOUSE_BUTTON_5, GLFW.GLFW_KEY_V -> cannon.auxiliaryAttack(player, item);
                        }
                    }

                    case DOOMFIST -> {
                        IBattleMode battleMode = player.getCapability(IBattleMode.BATTLE_MODE);

                        if (!battleMode.isInMode()) {
                            return;
                        }

                        battleMode.getController().keyInput(player, data.keyInput[0], data.keyInput[1], data.keyInput[2]);
                    }
                }
            });
        }
    }
}
